16 / 22

How can RTK Query work with GraphQL or custom fetch logic?

RTK Query can be integrated with GraphQL or any custom fetch logic by using a custom baseQuery. Instead of relying on REST-style endpoints, you can define your own query function that sends GraphQL requests or handles special request logic.

Ways to Work with GraphQL or Custom Fetch Logic
  1. 1

    Using fetchBaseQuery for Simple GraphQL Requests: Pass a static GraphQL query string and variables directly to the body of the request.

  2. 2

    Creating a Custom baseQuery: Use your own fetch or Axios logic to send requests and handle responses.

  3. 3

    Wrapping GraphQL Clients (e.g., Apollo, urql): Integrate RTK Query with existing GraphQL client instances to share caching and schema handling.

Example 1: Simple GraphQL Query with fetchBaseQuery

In this example, RTK Query sends a POST request containing a GraphQL query string in the request body. The hook useGetUsersQuery() automatically handles caching, loading, and error states.

Example 2: Using a Custom Base Query with fetch() or Axios

This custom base query gives you full flexibility — allowing you to handle GraphQL operations, custom headers, authentication, or even token refresh logic as needed.

In summary, RTK Query is backend-agnostic. Whether you use REST, GraphQL, or a completely custom fetch implementation, you can adapt it easily by defining the right baseQuery function.